<template>
  <div class="card" style="margin-bottom: 5px">
    <el-input clearable @clear="load" style="width: 260px; margin-right: 5px;" v-model="data.title" placeholder="请输入标题查询" :prefix-icon="Search"></el-input>
    <el-button type="primary" @click="load">查 询</el-button>
    <el-button type="info" @click="reset">重 置</el-button>
  </div>
  <div class="card"  style="margin-bottom: 5px" v-if="data.user.role === 'ADMIN'">
    <el-button type="primary" @click="headleAdd">新   增</el-button>
  </div>
  <div class="card" style="margin-bottom: 5px">
    <el-table @selection-change="handleSelectionChange" :data="data.tableData" style="width: 100%" :header-cell-style="{ color:'#333',backgroundColor:'#dde8ff'}">
      <el-table-column label="图书封面" width="100">
        <template #default="scope">
          <el-image :preview-src-list="[scope.row.img]" :preview-teleported="true" v-if="scope.row.img" :src="scope.row.img" alt="" style="width: 50px; height: 50px; display: block; border-radius: 5px"/>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="图书名字" />
      <el-table-column prop="price" label="图书价格" />
      <el-table-column prop="author" label="图书作者" />
      <el-table-column prop="num" label="剩余数量" />
      <el-table-column label="操作" width="100">
        <template #default="scope" v-if="data.user.role === 'ADMIN'">
          <el-button type="primary" icon="Edit" circle @click="headleEdit(scope.row)" ></el-button>
          <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)" ></el-button>
        </template>
        <template #default="scope" v-else>
          <el-button type="primary"  @click="borrow(scope.row)" >借阅</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="data.formVisible" title="图书信息" destroy-on-close width="30%">
      <el-form ref="formRef" :model="data.form" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="img" label="图书封面" >
          <el-upload
              action="http://localhost:9999/files/upload"
              :headers="{token: data.user.token}"
              :on-success="handleFileSuccess"
              list-type="picture"
          >
            <el-button type="primary">上传图书封面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="name" label="图书名字" >
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入图书名字"/>
        </el-form-item>
        <el-form-item prop="price" label="图书价格" >
          <el-input v-model="data.form.price" autocomplete="off" placeholder="请输入图书价格"/>
        </el-form-item>
        <el-form-item prop="author" label="图书作者" >
          <el-input v-model="data.form.author" autocomplete="off" placeholder="请输入图书作者"/>
        </el-form-item>
        <el-form-item prop="num" label="图书数量" >
          <el-input v-model="data.form.num" autocomplete="off" placeholder="请输入图书数量"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";

const formRef = ref()
const emit = defineEmits(["updateUser"])
const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  username: '',
  pageNum: 1,
  pageSize: 5,
  title: '',
  tableData: [],
  formVisible: false,
  form:{},
  rules: {
    img: [
      {required: true, message: '请上传图书封面', trigger: 'blur'},
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    name: [
      {required: true, message: '请填写图书名字', trigger: 'blur'},
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    price: [
      {required: true, message: '请填写图书价格', trigger: 'blur'},
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    author: [
      {required: true, message: '请填写图书作者', trigger: 'blur'},
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    num: [
      {required: true, message: '请填写剩余图书数量', trigger: 'blur'},
      // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
  }
})

// 数据获取查询按钮
const load = () =>{
  request.get('book/selectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      title:data.title
    }
  }).then(res =>{
    if(res.code === '200'){
      data.tableData =res.data.list
      emit("updateUser")
    }else {
      ElMessage.error(res.msg)
    }
  })
}
load()
// 重置按钮
const reset = () =>{
  data.title = ''
  load()
}

//  多选
const handleSelectionChange = (rows) => {
  data.rows = rows
}
// 修改保存按钮
const headleEdit = (row) =>{
  data.form = JSON.parse(JSON.stringify(row)) // 深拷贝
  data.formVisible = true
}

// 删除按钮
const del = (id) =>{
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '删除确认', {type: 'warning',}).then(res => {
    console.log(id)
    request.delete('/book/delete/'+id).then(res =>{
      if(res.code === '200'){
        ElMessage.success('删除成功')
        load()
      }
    }).catch(() => {
      ElMessage.error(res.msg)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  });
}

// 新增按钮
const headleAdd = () =>{
  data.form = {}
  data.formVisible = true
}

//  保存按钮 判断是新增还是修改
const save = () =>{
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if(valid){
      if(data.form.id){
        update()
      }else {
        add()
      }
    }
  })
}

// 修改编辑按钮
const update = () =>{
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if(!valid){
      return false
    }
    request.put('book/update',data.form).then(res =>{
      if(res.code === '200'){
        data.formVisible = false
        ElMessage.success('修改成功')
        load()
      }else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 新增保存按钮
const add = () =>{
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    console.log(valid)
    if(valid){
      request.post('book/add',data.form).then(res =>{
        if(res.code === '200'){
          data.formVisible = false
          ElMessage.success('新增成功')
          load()
        }else {
          ElMessage.error(res.msg)
        }
      })
    }
    })
}

const handleFileSuccess = (res) =>{
  data.form.img = res.data
}

const borrow = (row) =>{
  ElMessageBox.confirm('此操作将借阅该图书, 是否继续?', '借阅确认', {type: 'warning',}).then(res => {
    request.post('/record/add',{
      userId:data.user.id,
      bookId:row.id,
    }).then(res =>{
      if(res.code === '200'){
        ElMessage.success('借阅成功,等待管理员审核')
        load()
      }
    }).catch(() => {
      ElMessage.error(res.msg)
    })
  })
}
</script>

<style scoped>

</style>